package com.example.fw;

import java.util.List;
import java.util.Random;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;

public class HelperWithWebDriverBase extends HelperBase {

	private WebDriver driver;

	public HelperWithWebDriverBase(ApplicationManager manager) {
		super(manager);
		driver = manager.getWebDriverHelper().getDriver();
	}
	
	protected boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}

	protected void type(By locator, String name) {
		driver.findElement(locator).clear();
		driver.findElement(locator).sendKeys(name);
	}

	protected WebElement findElement(By locator) {
		return driver.findElement(locator);
	}

	protected List<WebElement> findElements(By locator) {
		return driver.findElements(locator);
	}

	protected void openUrl(String string) {
		driver.get(string);
	}
	
	protected void select(By locator, String item) {
		new Select(driver.findElement(locator)).selectByVisibleText(item);
	}

	protected void selectRandom(By locator) {
		Select select = new Select(driver.findElement(locator));
		List<WebElement> options = select.getOptions();
		if (options.size() > 0){
			int index = new Random().nextInt(options.size());
			options.get(index).click();
		}
	}
	/**
	 * Selects item by index.
	 * @param locator
	 * @param index
	 */
	protected void selectByIndex(By locator, int index) {
		Select select = new Select(driver.findElement(locator));
		List<WebElement> options = select.getOptions();
		if (options.size() > 0){			
			options.get(index).click();
		}
	}
	protected void click(By locator) {
		findElement(locator).click();
	}

	protected void submitCreation() {
		click(By.name("submit"));
	}

	protected void submitModification() {
		click(By.name("update"));
	}
}